package com.yxdj.common.rabbit.listener;

import com.alibaba.fastjson2.JSON;
import com.yxdj.common.rabbit.domain.MtyCorrelationData;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;


/**
 * @author 韩总
 */
@Slf4j
public class RabbitInitConfigApplicationListener implements ApplicationListener<ApplicationReadyEvent> {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        this.setupCallbacks();
    }

    private void setupCallbacks() {

		/**
         * 只确认消息是否正确到达 Exchange 中,成功与否都会回调
         *
         * @param correlation 相关数据  非消息本身业务数据
         * @param ack         应答结果
         * @param reason      如果发送消息到交换器失败，错误原因
         */
        this.rabbitTemplate.setConfirmCallback((correlationData, ack, reason) -> {
            if (ack) {
                //消息到交换器成功
                log.info("消息发送到Exchange成功：{}", correlationData);
            } else {
                //消息到交换器失败
                log.error("消息发送到Exchange失败：{}", reason);
                //重试，重新发送消息
                this.retrySendMsg(correlationData);
            }
        });

        /**
         * 消息没有正确到达队列时触发回调，如果正确到达队列不执行
         */
     	//默认情况下mandatory的值是false
        //但是只要配置开启了publisher-returns则mandatory的值就是true
        //this.rabbitTemplate.setMandatory(true);//是否让rabbitmq将失败的消息的信息再次返回给生产者
        this.rabbitTemplate.setReturnsCallback(returned -> {
            log.error("返回: " + returned.getMessage()
                      + "\n 响应码: " + returned.getReplyCode()
                      + "\n 响应消息: " + returned.getReplyText()
                      + "\n 交换机: " + returned.getExchange()
                      + "\n 路由: " + returned.getRoutingKey());

            //1.构建相关数据对象
            String redisKey = returned.getMessage().getMessageProperties().getHeader("spring_returned_message_correlation");
            String correlationDataStr = (String) redisTemplate.opsForValue().get(redisKey);
            MtyCorrelationData correlationData = JSON.parseObject(correlationDataStr, MtyCorrelationData.class);
            //2.调用消息重发方法
            this.retrySendMsg(correlationData);
        });
    }


    @SneakyThrows
    private void retrySendMsg(CorrelationData correlationData) {
        //获取相关数据
        MtyCorrelationData mtyCorrelationData = (MtyCorrelationData) correlationData;

        //获取redis中存放的重试次数
        //先将次数写回到redis中，再重发
        int retryCount = mtyCorrelationData.getRetryCount();
        if (retryCount >= 3) {
            //超过最大重试次数
            log.error("生产者超过最大重试次数，将失败的消息存入数据库用人工处理；给管理员发送邮件；给管理员发送短信；");
            return;
        }

        Thread.sleep(1000);

        //重发次数+1
        retryCount += 1;
        mtyCorrelationData.setRetryCount(retryCount);

        //将相关数据存入redis
        redisTemplate.opsForValue().set(
                mtyCorrelationData.getId(),
                JSON.toJSONString(mtyCorrelationData),
                10,
                TimeUnit.MINUTES);

        //重发消息
        log.info("进行消息重发！");
        rabbitTemplate.convertAndSend(
                mtyCorrelationData.getExchange(),
                mtyCorrelationData.getRoutingKey(),
                mtyCorrelationData.getMessage(),
                mtyCorrelationData
        );
    }
}
